class PptsController < ApplicationController
  layout "global", :only => [:index, :show]

  before_filter :item_out_of_range_validator, :only => [:show]
  before_filter :item_out_of_range_js_validator, :only =>[:run, :nex, :pre, :stop]
  before_filter :item_running_validator, :only =>[:nex, :pre, :stop]

  def index
    count = @@ppt.Presentations.Count
    @names = (1..count).map {|i| @@ppt.Presentations.Item(i).Name}
  end

  def show
    item = @@ppt.Presentations.Item(params[:id].to_i)
    @name = item.Name
    @title = @name
    @running = false
    begin
      @position = item.SlideShowWindow.View.CurrentShowPosition
      @running = true
      @title = "(#{@position}) #{@name}"
    rescue WIN32OLERuntimeError
    end
  end

  def run
    item = @@ppt.Presentations.Item(params[:id].to_i)
    item.SlideShowSettings.Run
    @position = item.SlideShowWindow.View.CurrentShowPosition
    response.headers['content-type'] = "application/javascript"
    str = escape_javascript "(#{@position}) #{item.Name}"
    render :text=>"changeTitle('#{str}')"
  end

  def stop
    item = @@ppt.Presentations.Item(params[:id].to_i)
    item.SlideShowWindow.View.Exit
    response.headers['content-type'] = "application/javascript"
    str = escape_javascript "#{item.Name}"
    render :text=>"changeTitle('#{str}')"
  end

  def nex
    item = @@ppt.Presentations.Item(params[:id].to_i)
    item.SlideShowWindow.View.Next
    @position = item.SlideShowWindow.View.CurrentShowPosition
    response.headers['content-type'] = "application/javascript"
    str = escape_javascript "(#{@position}) #{item.Name}"
    render :text=>"changeTitle('#{str}')"
  end

  def pre
    item = @@ppt.Presentations.Item(params[:id].to_i)
    item.SlideShowWindow.View.Previous
    @position = item.SlideShowWindow.View.CurrentShowPosition
    response.headers['content-type'] = "application/javascript"
    str = escape_javascript "(#{@position}) #{item.Name}"
    render :text=>"changeTitle('#{str}')"
  end

protected
  def item_out_of_range_validator
    count = @@ppt.Presentations.Count
    redirect_to ppts_path if params[:id].to_i > count
  end

  def item_out_of_range_js_validator
    count = @@ppt.Presentations.Count
    if params[:id].to_i > count
      response.headers['content-type'] = "application/javascript"
      render :text=>"window.location = '#{ppts_path}'"
    end
  end

  def item_running_validator
    begin
      @@ppt.Presentations.Item(params[:id].to_i).SlideShowWindow.View
    rescue WIN32OLERuntimeError
      @@ppt.Presentations.Item(params[:id].to_i).SlideShowSettings.Run
    end
  end

protected
  def escape_javascript(javascript)
    (javascript || '').gsub('\\','\0\0').gsub('</','<\/').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }
  end
end